import { t } from '@/hooks/useI18n';
import { isFunction } from '@sindresorhus/is';
import { kebabCase, pascalCase } from 'change-case';
import type { FormSchema, PlaceholderModel } from '../types';
import { omit } from 'es-toolkit';

export const setItemComponentSlots = (slotsProps: Recordable = {}): Recordable => {
  const ret: Recordable = {};
  for (const key in slotsProps) {
    const slotProp = slotsProps[key];
    const dashKey = kebabCase(key);
    ret[dashKey] = isFunction(slotProp) ? (...args: any[]) => slotProp(...args) : slotProp;
  }
  return ret;
};

/**
 * Returns a placeholder object based on the given schema.
 *
 * @param {FormSchema} schema
 * @returns {PlaceholderModel}
 */
export const getPlaceholder = (schema: FormSchema): PlaceholderModel => {
  const { component, componentProps } = schema;
  const textComponents = ['Input', 'InputPassword', 'InputNumber'];
  const selectComponents = ['Select', 'SelectV2'];
  const rangeComponents = ['datetimerange', 'daterange', 'monthrange', 'datetimerange', 'daterange'];

  if (textComponents.includes(component!)) {
    return { placeholder: componentProps?.placeholder ?? t('common.inputText') };
  }

  if (selectComponents.includes(component!)) {
    if (rangeComponents.includes(componentProps?.type)) {
      return {
        startPlaceholder: t('common.rangeStartText'),
        endPlaceholder: t('common.rangeEndText'),
        rangeSeparator: '-'
      };
    }

    return { placeholder: t('common.selectText') };
  }

  return {};
};

export const setComponentProps = (schema: FormSchema): Recordable => {
  const onEvents = schema.componentProps?.on ?? {};
  const newOnEvents: Recordable = {};
  for (const evt in onEvents) {
    // { input: (val) => console.log(val) }
    // { onInput: (val) => console.log(val) }
    newOnEvents[`on${pascalCase(evt)}`] = (...args: any[]) => onEvents[evt](...args);
  }

  const componentProps: Recordable = {
    clearable: true,
    ...schema.componentProps,
    ...newOnEvents
  };

  return omit(componentProps, ['on', 'slots']);
};
